<?php

namespace App\Http\Controllers\Api;

use App\Models\Trace;
use App\Models\User;
use Illuminate\Contracts\Logging\Log;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TraceController extends Controller
{
    

    

   

    /**
     * 保存定位信息
     * 百度地图 坐标转换 http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
     */
    public function save(Request $request)
    {        
        $ak = '5viKG8FFUlKS5HvoAWWrGyUWI0mOSGNN';
        

        /* 检验用户名和token*/
        $user = User::where(['username'=>$request->u,'token'=>$request->p])->first();
        if($user) {
        	$data = $request->all();
        	#  坐标转换  wgs84 to bd09ll
        	$url = 'http://api.map.baidu.com/geoconv/v1/?coords='.$data['longi'].','.$data['lati'].'&from=3&to=5&ak='.$ak;
        	$rs = $this->curl($url);
            $rs = json_decode($rs,true);
        	if($rs['status']==0) {
        		$data['longi'] = $rs['result'][0]['x'];
        		$data['lati']  = $rs['result'][0]['y'];
                
                # 经纬度转为地址
                 $url = 'http://api.map.baidu.com/geocoder/v2/?location='.$rs['result'][0]['y'].','.$rs['result'][0]['x'].'&output=json&pois=0&ak='.$ak;
                $address =  $this->curl($url);
                $address = json_decode($address,true);
                if($address['status'] == 0) {
                    $data['address'] = $address['result']['formatted_address'];
                } else {
                    echo '地理位置转换错误';die;
                }
        	} else {
        		echo '坐标转换错误';die;
        	}
        	Trace::create($data) ;
        	echo '成功';die;	
        } else {
        	echo '用户名或校验码错误';die;
        }

        
    }


    public function curl($url)
    {
    	$ch = curl_init();
	    $timeout = 10;
	    curl_setopt($ch, CURLOPT_URL, $url);
	    
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);	  
		
	    $contents = curl_exec($ch);
	    curl_close($ch);
	    return  $contents;
    }


   
}   
